/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.aptech.session.beans;

import entities.User;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Chien
 */
@Stateless
public class UserFacade extends AbstractFacade<User> {

    @PersistenceContext(unitName = "BluePumpkin-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UserFacade() {
        super(User.class);
    }

    public User checkEmail(String email) {
        Query createNamedQuery = em.createNamedQuery("User.findByEmail",User.class);
        createNamedQuery.setParameter("email", email);
        return (User) createNamedQuery.getSingleResult();
        
    }

    public User checkLogin(User user) {
        String hql = "SELECT u FROM User u WHERE u.userName = :userName AND u.passWord = :passWord";
        Query query = em.createQuery(hql);
        query.setParameter("userName", user.getUserName());
        query.setParameter("passWord", user.getPassWord());
        return (User) query.getSingleResult();
    }

    public List<User> getAllUserWithBirhday() {

        Calendar cal = Calendar.getInstance();

        int day = cal.get(Calendar.DAY_OF_MONTH);
        int month = cal.get(Calendar.MONTH) + 1;
        Query createQuery = em.createNamedQuery("User.findByIsActive");
        createQuery.setParameter("isActive", true);

        List<User> resultList = createQuery.getResultList();

        List<User> users = new ArrayList<User>();
        for (User user : resultList) {
            if (null != user.getBirthday()) {
                cal.setTime(user.getBirthday());
                int day_us = cal.get(Calendar.DAY_OF_MONTH);
                int month_us = cal.get(Calendar.MONTH) + 1;
                if (day == day_us && month == month_us) {
                    users.add(user);
                }
            }
        }

        return users;
    }
}
